package com.scfire.security

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import grails.converters.JSON
import com.scfire.baseInfo.Gson

import javax.servlet.http.HttpServletResponse

import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

import com.scfire.weixin.AutoReply
import com.scfire.weixin.WeiXinConstants

import grails.plugin.springsecurity.SpringSecurityUtils

class LoginController {
	def springSecurityService
	def authenticationTrustResolver
	
	def deviceInfoService
	def weiXinService
	
	def Log LOG = LogFactory.getLog(LoginController.class)
	
	/**
	 * 登陆首页
	 * Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
	 * @param null
	 * @return null
	 *
	 * **/
	def index() {
		
		if (springSecurityService.isLoggedIn()) {
			redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl
		}
		else {
			redirect action: 'auth', params: params
		}
		
	}
	
	/**
	 * 用户信息认证登陆
	 * @param null
	 * @return null
	 *
	 * **/
	def auth(){
		def userAgent = request.getHeader("User-Agent")
		String str = deviceInfoService.getDeviceInfo(userAgent)
		def gson = new Gson()
		def config = SpringSecurityUtils.securityConfig
		if (springSecurityService.isLoggedIn()) {
			withFormat{
				html {
					redirect uri: config.successHandler.defaultTargetUrl
					return
				}
				json {
					gson.setResult(true)
					gson.setCode(200)
					gson.setInfo(["text":"已经登陆"])
					render gson as JSON
				}
			}
			
		}else{
			withFormat {
				html {
					if("pc".equals(str)){
						String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
						render view: "auth", model: [postUrl: postUrl,
												   rememberMeParameter: config.rememberMe.parameter]
					}
					if("mobile".equals(str)){
						String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
						render view: "auth", model: [postUrl: postUrl,
												   rememberMeParameter: config.rememberMe.parameter]
					}
				}
				json {
					gson.setResult(false)
					gson.setCode(302)
					gson.setInfo(["text":"需要登陆"])
					render gson as JSON
				}
			}
		}
	}
	
	/**
	 * The redirect action for Ajax requests.
	 * @param null
	 * @return null
	 *
	 * **/
	def authAjax(){
		def userAgent = request.getHeader("User-Agent")
		
		String str=deviceInfoService.getDeviceInfo(userAgent)
		
		if("pc".equals(str)){
			response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
			response.sendError HttpServletResponse.SC_UNAUTHORIZED
		}else{
			redirect action: 'auth', params: params
		}
	}
/**
	 * create memu
	 * @param null
	 * @return null
	 *
	 * **/
	
	def createMenu(){
		weiXinService.createMenu()
		redirect(controller:"manage",action:"createMainMenu", params: [result: "ok"])
	}
	
	/**
	 * Show denied page.
	 * @param null
	 * @return null
	 *
	 * **/
	def denied(){
		if (springSecurityService.isLoggedIn() &&
			authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
		// have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
		redirect action: 'full', params: params
		}
	}
	
	/**
	 * Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
	 * @param null
	 * @return null
	 *
	 * **/
	def full(){
		def config = SpringSecurityUtils.securityConfig
		render view: 'auth', params: params,
		model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication),
				postUrl: "${request.contextPath}${config.apf.filterProcessesUrl}"]
	}
	
	/**
	 * Callback after a failed login. Redirects to the auth page with a warning message.
	 * @param null
	 * @return null
	 *
	 * **/
	def authfail(){
		def username = session[UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
		String msg = ''
		def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
		if (exception) {
			if (exception instanceof AccountExpiredException) {
				msg = g.message(code: "springSecurity.errors.login.expired")
			}
			else if (exception instanceof CredentialsExpiredException) {
				msg = g.message(code: "springSecurity.errors.login.passwordExpired")
			}
			else if (exception instanceof DisabledException) {
				msg = g.message(code: "springSecurity.errors.login.disabled")
			}
			else if (exception instanceof LockedException) {
				msg = g.message(code: "springSecurity.errors.login.locked")
			}
			else {
				msg = g.message(code: "springSecurity.errors.login.fail")
			}
		}

		if (springSecurityService.isAjax(request)) {
			render([error: msg] as JSON)
		}
		else {
			def format = request.getHeader("format")
			def iphone = request.getHeader("User-Agent")
			
			if(format == "json"){
				def gson = new Gson()
				gson.setResult(false)
				gson.setCode(401)
				gson.setInfo(["text":msg])
				render gson as JSON
			}else{
				flash.message = msg
				redirect action: 'auth', params: params
			}
			return

		}
	}
	
	/**
	 * The Ajax success redirect url.
	 * @param null
	 * @return null
	 *
	 * **/
	def ajaxSuccess(){
		
		render([success: true, username: springSecurityService.authentication.name] as JSON)
	}
	
	/**
	 * The Ajax denied redirect url.
	 * @param null
	 * @return null
	 *
	 * **/
	def ajaxDenied(){
		render([error: 'access denied'] as JSON)
	}
	
	/**
	 * Check register member username is exist.
	 * @param null
	 * @return null
	 *
	 * **/
	def checkSingleMemberExist(){
		def username = params.username
		def gson = new Gson()
		
		if(!username){
			render "true"
		}
		
		def member = Member.findByUsername(username)
		
		if(member){
			render "false"
		}else{
			render "true"
		}
	}
	
	/**
	 * The weixin login
	 * @param null
	 * @return null
	 *
	 * **/
	def weixinLogon(){
		
		def format = request.getHeader("format")		
		def userAgent = request.getHeader("User-Agent")
		def device = deviceInfoService.getDeviceInfo(userAgent)
		def config = SpringSecurityUtils.securityConfig
		
		if (springSecurityService.isLoggedIn()) {
			redirect uri: config.successHandler.defaultTargetUrl
			return
		}
		String oauthCallBack = WeiXinConstants.oauth_url+"?appid="+WeiXinConstants.appid+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.oauth_redirect_url)+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
		
		redirect(url:oauthCallBack)	
	}
	

	
	/**
	 * create AUTO REPLY
	 * @param null
	 * @return null
	 *
	 * **/
	def createAutoreply(){
		weiXinService.createAutoReplyContent()
		render "ok"
	}


}
